/*
 * @author zzr
 * @date: 2025/10/18  17:03
 * @description: 根据先序遍历和中序遍历来创建一颗二叉树
 */
public class Demo30 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int priIndex;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder, inorder, 0, inorder.length - 1);
    }

    private TreeNode buildTreeChild(int[] preorder, int[] inorder, int inbegin, int inend) {

        // 如果 inbegin > inend 则表明没有左树或者右树了
        if (inbegin > inend) {
            return null;
        }

        // 根据先序遍历数组中下标为 priIndex 来创建根节点
        TreeNode root = new TreeNode(preorder[priIndex]);

        // 从中序遍历中，找到根节点所在的下标
        int rootIndex = finIndex(inorder,inbegin,inend,preorder[priIndex]);

        if (-1 == rootIndex) {
            return null;
        }
        // 先序遍历的下标 preIndex 向后继续走
        priIndex++;

        // 递归创建左子树和右子树
        // 创建左子树的时候，inend 的值是 rootIndex - 1
        root.left = buildTreeChild(preorder, inorder, inbegin, rootIndex - 1);
        // 创建右子树的时候，inbegin 的值是 rootIndex + 1
        root.right = buildTreeChild(preorder, inorder, rootIndex + 1, inend);

        return root;
    }

    private int finIndex(int[] inorder, int inbegin, int inend, int key) {
        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
}
